package com.qgy.springsecurity.filters;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qgy.springsecurity.dao.UserDao;
import com.qgy.springsecurity.models.MyResult;
import com.qgy.springsecurity.models.bases.SysUser;
import com.qgy.springsecurity.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = null;
        try {
            jwt = extractJwtFromRequest(request);
            if (jwt != null && JwtUtil.parseJWT(jwt) != null) {
                Authentication authentication = getAuthenticationByToken(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            // 这里不需要特别处理异常，因为Spring Security会根据配置处理未授权的情况
        }

        filterChain.doFilter(request, response);
    }

    private Authentication getAuthenticationByToken(String jwt) {
        // 构造一个空的权限集合
        Collection<? extends GrantedAuthority> authorities = new ArrayList<>();

        // 使用带权限的构造方法
        return new UsernamePasswordAuthenticationToken(jwt, null, authorities);
    }

    private String extractJwtFromRequest(HttpServletRequest request){
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7); // 去掉 "Bearer " 前缀
        } else {
            return null;
        }
    }
}
